class Admin::RecommendSubjectsController < AdminController
  before_filter :find_recommend_subject, :only => [:show, :edit, :update, :destroy, :create_recommends]
  
  def index
    @recommend_subjects = RecommendSubject.valid.filter(params).paginate :page => params[:page], :per_page => 30
  end
  
  def show
  end
  
  def new
    @recommend_subject = RecommendSubject.new
  end
  
  def create
    @recommend_subject = RecommendSubject.new(params[:recommend_subject])
    if @recommend_subject.save
      flash[:notice] = "操作成功."
      redirect_to params[:save_and_new].blank? ? edit_admin_recommend_subject_path(@recommend_subject) : new_admin_recommend_subject_path
    else
      render 'new'
    end
  end
  
  def edit
    if params[:flag].to_i == 2
      @commends = Item.top.limit(10)
    elsif params[:flag].to_i == 3
      @commends = Item.recommend.limit(10)
    else
      @commends = Item.hot.limit(10)
    end
  end
  
  def update
    if @recommend_subject.update_attributes(params[:recommend_subject])
      flash[:notice] = "操作成功."
      redirect_to params[:save_and_new].blank? ? edit_admin_recommend_subject_path(@recommend_subject) : new_admin_recommend_subject_path
    else
      render 'edit'
    end
  end
  
  def destroy
    @recommend_subject.del
    flash[:notice] = "操作成功."
    redirect_to admin_recommend_subjects_url
  end
  
  def update_status
    if params[:ids].blank? or params[:ids].all?{|id| id.blank? }
      flash[:error] = "操作失败."
    else
      status = params[:status].blank? ? 0 : params[:status].to_i
      RecommendSubject.update_all("status = #{status}", "id IN (#{params[:ids].join(',')})")
      flash[:notice] = "操作成功."
    end
    redirect_to admin_recommend_subjects_url
  end
  
  def create_recommends
    if params[:recommend_ids].blank?
      flash[:error] = "操作失败."
    else
      flash[:notice] = "操作成功."
      params[:recommend_ids].each do |id|
        recommend = @recommend_subject.related_object.find_by_id(id)
        if recommend
          name = recommend.is_a?(ItemRating) ? recommend.title : recommend.name
          @recommend_subject.item_recommends.find_or_create_by_relation_id_and_name(id, name)
        end
      end
    end
    redirect_to edit_admin_recommend_subject_path(@recommend_subject)
  end
  
  def create_recommend
    item_recommend = ItemRecommend.new(params[:item_recommend])
    if item_recommend.save
      render :nothing => true
    else
      render :text => item_recommend.errors.full_messages.join('; '), :status => 404
    end
  end
  
  # just send ajax
  def delete_recommend
    ItemRecommend.find(params[:id]).destroy
    
    render :nothing => true
  end
  
  def get_subjects
    subjects = RecommendSubject.valid.find_all_by_flag(params[:flag])
    
    render :text => subjects.to_json
  end
  
  private

  def find_recommend_subject
    @recommend_subject = RecommendSubject.find(params[:id])
  end
end
